#!/usr/bin/perl

# EDIT THESE LINES#######################################
my $string_to_disable = "/usr/X11R6/lib/";
my $commenting_string = "# ";
my $path_to_file = "/var/db/dyld/";
my $file_to_edit = $path_to_file . "update-prebinding-paths.txt";
#############################################################


# does the target file exist?
my $target_disk = $ARGV[2];
my $target_file = $target_disk . $file_to_edit;
my @target_file_StatRec = stat($target_file);

if (!-e $target_file) {
	print(STDERR "Couldn't find conf file: " . $target_file . "\n");
	exit 0;
}

unless (open(CONFFILE, $target_file)) {
	print(STDERR "Couldn't open conf file: " . $target_file . "\n");
	exit 0;
}

# so first, designate a temp file and a place to back up the original
my $tempFilePathTemplate = $target_disk . $path_to_file . "com.apple.pkg.XXXX";
my $tempFilePath = `/usr/bin/mktemp $tempFilePathTemplate`;
chomp($tempFilePath);
my $backupPath = $target_file . ".applesaved";

# now open the temp file
unless (open(TEMPFILE, ">$tempFilePath")) {
	print(STDERR "Couldn't open temp file: " . $tempFilePath . "\n");
	close(CONFFILE);
	exit 0;
}

# Now it's loopy time
# For each line in the input file, if it begins with the $string_to_disable, 
#	write it to the temp file with the commenting string prepended.
# Otherwise just copy it.
my $dirtyBit = 0;
while (my $inputLine = <CONFFILE>)
{
	if ($inputLine =~ m!^$string_to_disable!)
	{
		print(TEMPFILE $commenting_string . $inputLine);
		$dirtyBit = 1;
	} else {
		print(TEMPFILE $inputLine);
	}
}

# we're all done copying/modifying
close(CONFFILE);
close(TEMPFILE);

# did we do anything important? If not, blow away the temp file and exit.
if ($dirtyBit == 0)
{
	print(STDERR $target_file . " was unchanged.\n");
	unlink($tempFilePath);
	exit 0;
}

# now give the temp file the right metadata
if(chmod($target_file_StatRec[2], $tempFilePath)) {
	if(chown($target_file_StatRec[4], $target_file_StatRec[5], $tempFilePath)) {
	
		# delete any old backups that may be lurking
		unlink($backupPath);

		# point the backup's file pointer at the current file
		if(link($target_file, $backupPath)) {
			# and rename the temp to the current file name.
			if(rename($tempFilePath, $target_file)) {
				print(STDERR $target_file . " was successfully updated.\n");
			} else {
				print(STDERR "An error occurred attempting to update " . $target_file . ".  The previous file is still active.\n");
			}
		} else {
			print(STDERR "An error occurred attempting to back up " . $target_file . ".  No updating will occur.\n");
		}
	} else {
		print(STDERR "An error occurred setting file ownership for " . $tempFilePath . ".  No updating will occur.\n");
	}
} else {
	print(STDERR "An error occurred setting file mode for " . $tempFilePath . ".  No updating will occur.\n");
}

unlink($tempFilePath);


exit 0;